
from random import randint

output_names = {'user_name': '玩家姓名', 'game_times': '总游戏次数', 'fastest': '最快猜出的轮数', 'all_times': '猜过的总轮数'}
dic = {'user_name': '', 'game_times': 0, 'average': 0.00, 'fastest': 0, 'all_times': 0}


def dict_game_info(key, value):
    s_key = str(key)
    if s_key in dic:
        dic[str(key)] = value


def write_file(data):
    keys = data.keys()

    out = open('output.txt', 'w')
    s = ""

    for key in keys:
        if key in output_names:
            s = s + output_names.get(key) + "：" + str(dic.get(key)) + "；"

    out.write(s)
    out.close()


def get_user_info():
    user_name = input("请输入你的名字：")
    dict_game_info('user_name', user_name)


def output():
    print("%s，你已经玩了%d次，最少%d轮猜出答案，平均%s轮猜出答案" % (dic.get('user_name'), dic.get('game_times'), dic.get('fastest'), '%.2f' % float(dic.get('average'))))


def guess():
    # 总游戏次数加一
    game_times = dic.get('game_times')
    dic['game_times'] = game_times + 1

    # 一次游戏过程
    guess_num = randint(1, 100)
    times = 0
    while True:
        a = int(input("请猜一个 1 - 100 的数字："))
        times += 1
        if a < guess_num:
            print("猜小了，再试试")
        elif a > guess_num:
            print("猜大了，再试试")
        else:
            print("猜对了，你一共猜了%d轮" % times)
            break

    # 更新猜过的总轮数
    all_times = dic.get('all_times')
    dic['all_times'] = all_times + times

    # 更新最快猜出的轮数
    fastest = dic.get('fastest')
    if fastest == 0:
        dic['fastest'] = times
    elif times < fastest:
        dic['fastest'] = times

    # 更新平均轮数
    average = dic.get('all_times') / dic.get('game_times')
    dic['average'] = average

    # 打印游戏数据
    output()

    game = input('输入任意键继续，回车退出')
    if not game:
        # 游戏数据写入文件
        write_file(dic)
        print("退出游戏，欢迎下次再来")
    else:
        guess()


def start():
    # 获取玩家名称
    get_user_info()
    # 开始游戏
    guess()


start()
